# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)
diffData <- read_csv("../../potential/Markers.csv")

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
  .$Metabolite
data <- read.csv(opt$i, header = T) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  column_to_rownames("SampleID") %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame()

classData <- read_csv(opt$i) %>%
  select(c("Metabolite", "Class"))

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

svmRs <- svm(x, y, type = 'C', kernel = "linear")
unclass(svmRs)
imp <- (t(svmRs$coefs) %*% svmRs$SV)[1,]^2;
names(imp) <- colnames(x);
impData <- imp %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  set_colnames(c("Metabolite", "Value")) %>%
  arrange(Value) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite)))
impData
print(head(impData))

plotData <- impData
outData <- plotData %>%
  arrange(desc(Value)) %>%
  rename(`SVM-RFE` = Value) %>%
  left_join(classData, by = c("Metabolite")) %>%
  select(c("Metabolite","Class", "SVM-RFE"))
outFileName <- paste0(parent, "/SVM_Imp_Rank.csv")
write.csv(outData, outFileName, row.names = F)






